// 获取画布和上下文
const canvas = document.getElementById('game-canvas');
const ctx = canvas.getContext('2d');

// 画布尺寸
const CANVAS_WIDTH = 800;
const CANVAS_HEIGHT = 600;
canvas.width = CANVAS_WIDTH;
canvas.height = CANVAS_HEIGHT;

// 得分
let score = 0;
const scoreElement = document.getElementById('score');

// 直升机属性
const helicopter = {
    x: 50,
    y: CANVAS_HEIGHT / 2,
    width: 50,
    height: 30,
    dy: 0,
    image: new Image()
};
helicopter.image.src = 'helicopter.png';

// 障碍物数组
let obstacles = [];
// 障碍物间隔
const OBSTACLE_INTERVAL = 200;
// 障碍物移动速度
const OBSTACLE_SPEED = 3;
// 重力
const GRAVITY = 0.2;
// 上升力
const LIFT = -5;

// 绘制直升机
function drawHelicopter() {
    ctx.drawImage(helicopter.image, helicopter.x, helicopter.y, helicopter.width, helicopter.height);
}

// 绘制障碍物
function drawObstacles() {
    obstacles.forEach(obstacle => {
        ctx.drawImage(obstacle.image, obstacle.x, obstacle.y, obstacle.width, obstacle.height);
    });
}

// 移动直升机
function moveHelicopter() {
    helicopter.dy += GRAVITY;
    helicopter.y += helicopter.dy;

    // 边界检测
    if (helicopter.y < 0) {
        helicopter.y = 0;
        helicopter.dy = 0;
    } else if (helicopter.y + helicopter.height > CANVAS_HEIGHT) {
        gameOver();
    }
}

// 创建障碍物
function createObstacle() {
    const obstacle = {
        x: CANVAS_WIDTH,
        y: Math.random() * (CANVAS_HEIGHT - 50),
        width: 30,
        height: 50,
        image: new Image()
    };
    obstacle.image.src = 'obstacle.png';
    obstacles.push(obstacle);
}

// 移动障碍物
function moveObstacles() {
    for (let i = obstacles.length - 1; i >= 0; i--) {
        const obstacle = obstacles[i];
        obstacle.x -= OBSTACLE_SPEED;

        // 检查碰撞
        if (
            helicopter.x < obstacle.x + obstacle.width &&
            helicopter.x + helicopter.width > obstacle.x &&
            helicopter.y < obstacle.y + obstacle.height &&
            helicopter.y + helicopter.height > obstacle.y
        ) {
            gameOver();
        }

        // 移除超出屏幕的障碍物
        if (obstacle.x + obstacle.width < 0) {
            obstacles.splice(i, 1);
            score++;
            scoreElement.textContent = score;
        }
    }
}

// 游戏结束
function gameOver() {
    alert(`游戏结束！你的得分是: ${score}`);
    // 重置游戏
    score = 0;
    scoreElement.textContent = score;
    helicopter.y = CANVAS_HEIGHT / 2;
    helicopter.dy = 0;
    obstacles = [];
}

// 处理键盘事件
document.addEventListener('keydown', function (event) {
    if (event.key === ' ') {
        helicopter.dy = LIFT;
    }
});

// 主游戏循环
let frameCount = 0;
function gameLoop() {
    ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);

    drawHelicopter();
    drawObstacles();
    moveHelicopter();
    moveObstacles();

    frameCount++;
    if (frameCount % OBSTACLE_INTERVAL === 0) {
        createObstacle();
    }

    requestAnimationFrame(gameLoop);
}

// 初始化游戏
gameLoop();